package main

import (
	"bufio"
	log "github.com/sirupsen/logrus"
	"io"
	"os"
)

func init() {
	console := log.New()
	console.SetFormatter(&log.TextFormatter{
		ForceColors:     true,
		FullTimestamp:   true,
		TimestampFormat: "2006-01-02 15:04:05",
	})
	inputfile := log.New()
	inputfile.SetFormatter(&log.TextFormatter{
		FullTimestamp:   true,
		TimestampFormat: "2006-01-02 15:04:05",
	})
	log.SetLevel(log.InfoLevel)
	log.SetReportCaller(true)
}
func main() {
	/*
		实现将日志输出到文件中
		content := "hello 北京"
		file, err := os.OpenFile("./test.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
		if err != nil {
			log.Error("打开%s文件失败", "test.log")
			return
		}
		log.SetOutput(file)
		defer file.Close()
		writer := bufio.NewWriter(file)
		//将数据先写到缓存中
		for i := 0; i < 4; i++ {
			_, err := writer.WriteString(content + "\n")
			logWrite := log.WithFields(log.Fields{
				"appid":   i,
				"content": content,
			})
			if err == nil {
				logWrite.Info("写数据成功")
			} else {
				logWrite.Error("写数据失败")
				break
			}
		}
		err = writer.Flush()
		if err != nil {
			log.Error("将数据从内存持久化到文件失败")
			return
		} //将缓存中的内容写入文件中
	*/
	/*
		实现将日志输出到文件和控制台
	*/
	content := "hello 北京"
	/*
			写法一
		writes := []io.Writer{
			os.Stdout,
			file,
		}
		log.SetOutput(io.MultiWriter(writes...))
	*/
	/*
		写法二 log.SetOutput(io.MultiWriter(file,os.Stdout))
	*/
	file, err := os.OpenFile("./test.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Error("打开%s文件失败", "test.log")
		return
	}
	log.SetOutput(io.MultiWriter(file, os.Stdout))
	defer file.Close()
	writer := bufio.NewWriter(file)
	//将数据先写到缓存中
	for i := 0; i < 4; i++ {
		_, err := writer.WriteString(content + "\n")
		logWrite := log.WithFields(log.Fields{
			"appid":   i,
			"content": content,
		})
		if err == nil {
			logWrite.Info("写数据成功")
		} else {
			logWrite.Error("写数据失败")
			break
		}
	}
	err = writer.Flush()
	if err != nil {
		log.Error("将数据从内存持久化到文件失败")
		return
	} //将缓存中的内容写入文件中
}
